package com.itheima.service.impl;

import com.itheima.mapper.CatematerMapper;
import com.itheima.pojo.Catemater;
import com.itheima.service.CatematerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

@Service
public class CatematerServiceImpl implements CatematerService {

    @Autowired
    private CatematerMapper catematerMapper;

    @Override
    public List<Catemater> findAll() {
        //查询所有分类
        List<Catemater> catematers = catematerMapper.all();
        //找到所有顶级分类
        List<Catemater> parent = catematers.stream()
                .filter(c -> Objects.equals(c.getParenId(), 0))
                .toList();

        // 子分类筛选
        List<Catemater> children = catematers.stream()
                .filter(c -> c.getParenId() != null && c.getParenId() > 0)
                .toList();
        //递归查找
        parent.forEach(c -> findEach(c,children));
        return catematers;
    }




    private void findEach(Catemater catemater, List<Catemater> children) {
        List<Catemater> list = children.stream().filter(c -> Objects.equals(c.getParenId(), catemater.getId())).toList();

        if(!CollectionUtils.isEmpty(list)){
            list.forEach(d -> findEach(d,children));
        }
        catemater.setCatematerList(list);
    }
}
